import { appConfig } from "@/config";
import { tansParams } from "@/utils/common";
import { buildUUID, jumpLoginPage } from "@/utils/util";
import { getKKToken } from "@/utils/storageUtil";
import kkToast from "@/utils/kkToast";
import { version } from "../../package.json";
import createEncryption from "@/utils/createEncryption";

const result_code = 10000;

const timeout = 100000;
const rqeuestUrl = appConfig.baseUrl;

const request = (config: any) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  const systemInfo = uni.getSystemInfoSync();
  config.header = {
    "Content-Type": config.contentType || "application/json",
    "kk-request-id": `${buildUUID()}${new Date().getTime()}`,
    "kk-version": version,
    "kk-from": "wechat-app",
    "kk-os": systemInfo.osName || "",
    "kk-modle": systemInfo.model || "",
    "kk-ip": "",
    "tenant-id": "",
    "org-id": "",
  };
  if (!isToken) {
    config.header["kk-token"] = getKKToken();
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + "?" + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || "get",
        timeout: config.timeout || timeout,
        url: getRequestUrl(config),
        data: getEncryptionData(config.data, config.method || "get"),
        header: config.header,
        dataType: "json",
      })
      .then((response) => {
        let { data } = response;
        if (!data) {
          // 返回“[HTTP]请求没有返回值”;
          throw new Error();
        }
        const code = Number((data as AnyObject).code || result_code);
        // 获取错误信息
        const msg =
          (data as AnyObject).msg ||
          (data as AnyObject).message ||
          "系统未知错误，请反馈给管理员";
        if (code === 10000 || code === 200) {
          if (data) {
            return resolve(data);
          }
          return resolve({});
        } else {
          if (code === 11105 || code === 10041) {
            // 登录已失效，请重新登录
            kkToast.showToast("登录已失效，请重新登录");
            jumpLoginPage();
          } else {
            if (msg) kkToast.showToast(msg);
          }
          return reject({ code, msg });
        }
      })
      .catch((error) => {
        const response = error.response || {};
        const status = response.status || 400;
        const responseData = response.data || {};
        const message = responseData.msg || error.message || status;
        if (message) {
          kkToast.showToast(response);
        }
        reject(error);
      });
  });
};

const getEncryptionData = (data: any, method: string) => {
  if (method.toLowerCase() === "post") {
    const postBodyEncryption = createEncryption("b2814071841", "awo6ureum8bn");
    data = postBodyEncryption(getKKToken(), data);
  }
  return data;
};

const getRequestUrl = (config: any) => {
  // #ifdef MP-WEIXIN
  if (config.isBigClient) {
    return appConfig.bigClientUrl + config.url;
  }
  return config.baseUrl || rqeuestUrl + config.url;
  // #endif

  // #ifdef H5
  // return appConfig.baseApi + config.url;
  if (config.isBigClient) {
    return appConfig.bigClientUrl + config.url;
  }
  return config.baseUrl || rqeuestUrl + config.url;
  // #endif
};

export default request;
